package m2;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.List;
import java.util.Scanner;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/9/24 17:34
 */
public class Producer {

    static String[] msgs = {
            "15103111039,创建",
                                "15103111065,创建",
            "15103111039,付款",
                                                    "15103117235,创建",
                                "15103111065,付款",
                                                    "15103117235,付款",
                                "15103111065,完成",
            "15103111039,推送",
                                                    "15103117235,完成",
            "15103111039,完成"
    };

    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {

        // 创建生产者对象
        DefaultMQProducer p = new DefaultMQProducer("prod-group2");
        // 设置name server
        p.setNamesrvAddr("192.168.64.141:9876");
        // 启动连接
        p.start();
        // 创建消息封装对象 Message()
        while (true) {
            for (String s : msgs) {
                Long orderId = Long.valueOf(s.split(",")[0]);

                Message msg = new Message("topic2", s.getBytes());
                SendResult sendResult = p.send(msg, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                        Long orderId = (Long) o;
                        int index = (int) (orderId % list.size());
                        return list.get(index);
                    }
                }, orderId);
                System.out.println(sendResult);
            }
        }
    }
}
